package com.ynwa;

import java.lang.reflect.*;

/**
 * @author gzd
 * @date 2018-05-13 下午7:35
 * @desc jdk动态代理
 */
public class JdkProxy {

    private interface ISay {
        void say();
    }

    private static class Say implements ISay {

        @Override
        public void say() {
            System.out.println("hello jdk proxy!");
        }
    }

    private static class MyInvocationHandler implements InvocationHandler {

        private Object target;

        public MyInvocationHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("--调用之前--");

            Object invoke = method.invoke(target, args);

            System.out.println("--调用之后--");
            return invoke;
        }
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

        Class<?> proxyClass = Proxy.getProxyClass(JdkProxy.class.getClassLoader(), ISay.class);
        Constructor<?> constructor = proxyClass.getConstructor(InvocationHandler.class);
        ISay iSay = (ISay) constructor.newInstance(new MyInvocationHandler(new Say()));

        iSay.say();

    }
}
